<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="文件标题" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          placeholder="请输入文件标题"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['company:document:add']"
          >发布红头文件公告</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table fit v-loading="loading" border :data="dataList">
      <el-table-column width="50" label="ID" prop="noticeId" />
      <el-table-column
        align="center"
        label="标题"
        prop="noticeTitle"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-link @click="handleDetail(scope.row.noticeId)" type="primary">{{
            scope.row.noticeTitle
          }}</el-link>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope"> 已发布 </template>
      </el-table-column>
      <el-table-column align="center" label="关联员工" prop="userName" />

      <el-table-column align="center" label="发布时间" prop="createTime" />
      <el-table-column label="是否显示" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isTop"
            active-value="1"
            inactive-value="0"
            @change="handleIsTop(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-hasPermi="['company:document:info']"
            @click="handleDetail(scope.row.noticeId)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['company:document:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['company:document:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改公司公告对话框 -->
    <el-dialog
      title="红头文件公告"
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="文件分类" prop="noticeType">
              <el-select
                v-model="form.noticeType"
                placeholder="请选择文件分类"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.sys_red_doc_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文件内容" prop="noticeContent">
              <FileUpload v-model="form.noticeContent"></FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关联个人" prop="isRel">
          <el-radio-group v-model="form.isRel">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isRel == 1" label="员工姓名" prop="redDocVos">
          <el-tag
            :key="index"
            v-for="(item, index) in nextUser"
            closable
            :disable-transitions="false"
            @close="handleClose('next', item)"
          >
            {{ item.nickName }}
          </el-tag>
          <el-button
            class="button-new-tag"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            circle
            @click="onSelectNextUsers"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="rowDetail.noticeTitle"
      :visible.sync="detailOPen"
      width="600px"
      append-to-body
    >
      <transition-group
        class="upload-file-list el-upload-list el-upload-list--text"
        name="el-fade-in-linear"
        tag="ul"
      >
        <li
          :key="file"
          class="el-upload-list__item ele-upload-list__item-content"
          v-for="(file, index) in rowDetail.noticeContent
            ? rowDetail.noticeContent.split(',')
            : []"
        >
          <el-link :href="`${file}`" :underline="false" target="_blank">
            <span class="el-icon-document"> {{ getFileName(file) }} </span>
          </el-link>
        </li>
      </transition-group>

      <div v-if="rowDetail.isRel == 1">关联员工：{{ rowDetail.userName }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailOPen = false">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="userData.title"
      :visible.sync="userData.open"
      width="60%"
      append-to-body
    >
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>部门列表</span>
            </div>
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
              />
              <el-tree
                :data="deptOptions"
                :props="deptProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-table
            ref="userTable"
            :key="userData.type"
            height="500"
            v-loading="userLoading"
            :data="userList"
            highlight-current-row
            @current-change="changeCurrentUser"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              v-if="userData.type === 'copy' || userData.type === 'next'"
              width="55"
              type="selection"
            />
            <el-table-column v-else width="30">
              <template slot-scope="scope">
                <el-radio :label="scope.row.userId" v-model="currentUserId">{{
                  ""
                }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="用户名" align="center" prop="nickName" />
            <el-table-column label="手机" align="center" prop="phonenumber" />
            <el-table-column label="部门" align="center" prop="dept.deptName" />
          </el-table>
          <pagination
            :total="total"
            :page.sync="queryParams1.pageNum"
            :limit.sync="queryParams1.pageSize"
            @pagination="getListUser"
          />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userData.open = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { selectUser, deptTreeSelect } from "@/api/system/user";

import {
  isTopChange,
  noticeList,
  noticeAdd,
  statusChange,
  noticeEdit,
  noticeDel,
  noticeInfo,
} from "@/api/company/index.js";
import { listFileManager, delFileManager } from "@/api/system/fileManager.js";
export default {
  name: "Notice",
  dicts: ["sys_red_doc_type"],
  data() {
    return {
      deptProps: {
        children: "children",
        label: "label",
      },
      userData: {
        title: "",
        type: "",
        open: false,
      },
      nextUser: [],
      dataList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      form: {
        status: 0,
        noticeContent: "",
        noticeType: "1",
        isRel: "0",
      },
      // 表单校验
      rules: {
        noticeType: [
          { required: true, message: "文件分类不能为空", trigger: "change" },
        ],
        noticeTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" },
        ],
        noticeContent: [
          { required: true, message: "文件不能为空", trigger: "change" },
        ],
        noticeContent: [
          { required: true, message: "内容不能为空", trigger: "blur" },
        ],
        status: [
          { required: false, message: "类型不能为空", trigger: "change" },
        ],
        isRel: [
          { required: true, message: "是否关联不能为空", trigger: "change" },
        ],
      },
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        busType: 3,
      },
      rowDetail: {},
      detailOPen: false,
      deptOptions: [],
      userLoading: false,
      queryParams1: {
        deptId: undefined,
      },
      userMultipleSelection: [],
      // 部门名称
      deptName: undefined,
      userList: [],
    };
  },
  created() {
    this.getList();
    if (this.$route.query.id) {
      this.handleDetail(this.$route.query.id);
    }
    if (this.$route.query.add) {
      this.handleAdd();
    }
  },
  methods: {
    handleIsTop(row) {
      let text = row.isTop === "1" ? "置顶" : "取消置顶";
      this.$modal
        .confirm('确认要"' + text + '""' + row.noticeTitle + '"红头文件吗？')
        .then(function () {
          return isTopChange(row.noticeId, row.isTop);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isTop = row.isTop === "0" ? "1" : "0";
        });
    },
    handleStatusChange(row) {
      let text = row.status === "1" ? "显示" : "隐藏";
      this.$modal
        .confirm('确认要"' + text + '""' + row.noticeTitle + '"红头文件吗？')
        .then(function () {
          return statusChange(row.noticeId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    onSelectNextUsers() {
      this.userMultipleSelection = this.nextUser;
      this.onSelectUsers("关联员工", "next");
    },
    onSelectUsers(title, type) {
      this.userData.title = title;
      this.userData.type = type;
      this.getTreeSelect();
      this.getListUser();
      this.userData.open = true;
    },
    /** 查询部门下拉树结构 */
    getTreeSelect() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询用户列表 */
    getListUser() {
      this.userLoading = true;
      selectUser(this.addDateRange(this.queryParams1, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.toggleSelection(this.userMultipleSelection);
          this.userLoading = false;
        }
      );
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams1.deptId = data.id;
      this.getListUser();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userMultipleSelection = selection;
    },
    changeCurrentUser(val) {
      this.currentUserId = val.userId;
    },
    toggleSelection(selection) {
      if (selection && selection.length > 0) {
        this.$nextTick(() => {
          selection.forEach((item) => {
            let row = this.userList.find((k) => k.userId === item.userId);
            this.$refs.userTable.toggleRowSelection(row);
          });
        });
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    submitUserData() {
      let type = this.userData.type;
      if (
        !this.userMultipleSelection ||
        this.userMultipleSelection.length <= 0
      ) {
        this.$modal.msgError("请选择用户");
        return false;
      }
      let userIds = this.userMultipleSelection.map((k) => k.userId);
      this.nextUser = this.userMultipleSelection;
      this.userData.open = false;
    },
    // 关闭标签
    handleClose(type, tag) {
      let userObj = this.userMultipleSelection.find(
        (item) => item.userId === tag.userId
      );
      console.log(userObj, tag);
      this.userMultipleSelection.splice(
        this.userMultipleSelection.indexOf(userObj),
        1
      );
      this.nextUser = this.userMultipleSelection;
      // 设置抄送人ID
      if (this.nextUser && this.nextUser.length > 0) {
        const val = this.nextUser.map((item) => item.id);
        this.taskForm.nextUserIds = val instanceof Array ? val.join(",") : val;
      } else {
        this.taskForm.nextUserIds = "";
      }
    },
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.nextUser);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.isRel == 1 && this.nextUser.length == 0) {
            this.$modal.msgWarning("请选择关联员工");
            return;
          } else if (this.form.isRel == 1 && this.nextUser.length != 0) {
            this.form.redDocVos = this.nextUser.map((item) => {
              return { isRelUserId: item.userId };
            });
          }

          if (this.form.noticeId != undefined) {
            noticeEdit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.busType = 3;
            noticeAdd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDetail(row) {
      this.detailOPen = true;
      // this.rowDetail = JSON.parse(JSON.stringify(row));
      noticeInfo(row).then((res) => {
        this.rowDetail = res.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm("form");
      if (row.redDocVos) {
        let u = row.redDocVos.map((item) => {
          return {
            nickName: item.nickName,
            userId: item.isRelUserId,
          };
        });
        console.log(u);
        this.nextUser = u;
        this.userMultipleSelection = this.nextUser;
      } else {
        this.nextUser = [];
        this.userMultipleSelection = this.nextUser;
      }
      this.form = JSON.parse(JSON.stringify(row));
      this.form.status = row.status.toString();
      console.log(this.form);
      this.open = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除标题为"' + row.noticeTitle + '"的数据项？')
        .then(function () {
          return noticeDel(row.noticeId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleAdd() {
      this.resetForm("form");
      (this.form = {
        status: 0,
        noticeType: "1",
        isRel: "0",
      }),
        (this.open = true);
      this.nextUser = [];
    },
    cancel() {
      this.open = false;
      this.detailOPen = false;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listFileManager(this.queryParams).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style scoped lang="scss">
.button-new-tag {
  margin-left: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
